var Harm = function() {

    var datalist_url = $('.datalist_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var redirect_url = $('.redirect_url').val();
    var save_url = $('.save_url').val();

    var cropsData_url = $('.cropsData_url').val();
    var medicamentsData_url = $('.medicamentsData_url').val();

    var isLoadMedicamentsTable = false;


    var initTable = function() {
        var table = $('#data-table');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                //"ordering": false, // 禁止排序
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: datalist_url,
                },
                "autoWidth": false,
                "columns": [
                    {"data": "name"},
                    {
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            var html = '';
                            if(ADMININFO.type == 0 || row.createOper == ADMININFO.id){
                                html += '<a href="'+edit_url+'?id='+row.id+'" type="button" class="btn btn-success">编辑</a>';
                                html += '<button type="button" class="btn btn-danger delete-btn">删除</button>';
                            }else{
                                //html += '<button type="button" class="btn btn-success" disabled="disabled">编辑</button>';
                                //html += '<button type="button" class="btn btn-danger" disabled="disabled">删除</button>';
                            }

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": true,
                "stateSaveParams": function (settings, data) {
                    var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }
                },
                "order": [
                    [0, "desc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [1]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });
        }

        // 筛选
        $('#doSearch').on('click', function(event){
            var param = $('#searchForm').serializeObject();

            tableSearch(table, param);
        });

        // 删除
        table.on('click', '.delete-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var text = '是否要删除这条数据？';
            var title = '请确认';
            var confirmBtn = '确定';
            var cancelBtn = '取消';
            event.preventDefault();

            layer.confirm(
                text,
                {
                    title: title,
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    layer.close(index);
                    var url = delete_url;
                    var data = {'id':id};
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType : 'json',
                        success: function (data) {
                            layer.msg(data.msg);
                            if(data.code == 1){
                                _this.parents('tr').remove();
                            }
                        }
                    });
                }
            );
        });
    };

    // 农作物 Table
    var initCropsTable = function() {
        var table = $('#crops-datatable');

        if(table.length > 0){
            var typeId = $('select[name=croptypeId]').val();
            table.dataTable({
                "processing": true,
                "ordering": false, // 禁止排序
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: cropsData_url,
                    data: {'typeId': typeId}
                },
                "autoWidth": false,
                "columns": [
                    {
                        "data": "imgUrl",
                        "render": function(data, type, row, meta) {
                            return '<img src="'+data+'" style="width: 40px;height: 40px;"/>';
                        }
                    },
                    {"data": "name"},
                    {
                        "width": "15%",
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            //var html = '<button type="button" class="btn btn-success select-btn">选择</button>';
                            var html = '';
                            html += '<div class="md-checkbox has-success">';
                            html += '<input type="checkbox" id="check-medicament'+row.id+'" class="md-check check-item" name="id[]" value="'+row.id+'" data-name="'+row.name+'">';
                            html += '<label for="check-medicament'+row.id+'">';
                            html += '<span class="inc"></span>';
                            html += '<span class="check"></span>';
                            html += '<span class="box"></span>';
                            html += '选择 ';
                            html += '</label>';
                            html += '</div>';

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": true, // 不重新加载表格内容
                //"destroy": false,
                "columnDefs": [{
                    "orderable": false,
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnCreatedRow": function(nRow, aData, iDataIndex){
                    var cropIds = $('.cropIds').val();
                    if(cropIds.indexOf(aData['id']) >= 0) {
                        $(nRow).find('input[type=checkbox]').prop('checked', true);
                        $(nRow).find('input[type=checkbox]').prop('disabled', true);
                    }
                },
                "fnInitComplete": function() {
                    //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });
        }

        // 筛选
        $('.doSearch').on('click', function(event){
            var param = $(this).parents('.searchForm').serializeObject();

            tableSearch(table, param);
        });
    };

    // 药剂 Table
    var initMedicamentsTable = function() {
        var table = $('#medicaments-datatable');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                "ordering": false, // 禁止排序
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: medicamentsData_url,
                    data: {}
                },
                "autoWidth": false,
                "columns": [
                    {"data": "name"},
                    {
                        "width": "15%",
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            //var html = '<button type="button" class="btn btn-success select-btn">选择</button>';
                            var html = '';
                            html += '<div class="md-checkbox has-success">';
                            html += '<input type="checkbox" id="check-medicament'+row.id+'" class="md-check check-item" name="id[]" value="'+row.id+'" data-name="'+row.name+'">';
                            html += '<label for="check-medicament'+row.id+'">';
                            html += '<span class="inc"></span>';
                            html += '<span class="check"></span>';
                            html += '<span class="box"></span>';
                            html += '选择 ';
                            html += '</label>';
                            html += '</div>';

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": true, // 不重新加载表格内容
                //"destroy": false,
                "columnDefs": [{
                    "orderable": false,
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnCreatedRow": function(nRow, aData, iDataIndex){
                    var medicamentIds = $('.medicamentIds').val();
                    if(medicamentIds.indexOf(aData['id']) >= 0) {
                        $(nRow).find('input[type=checkbox]').prop('checked', true);
                        $(nRow).find('input[type=checkbox]').prop('disabled', true);
                    }
                },
                "fnInitComplete": function() {
                    //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });

            isLoadMedicamentsTable = true;
        }

        // 筛选
        $('.doSearch').on('click', function(event){
            var param = $(this).parents('.searchForm').serializeObject();

            tableSearch(table, param);
        });
    };

    var tableSearch = function(table, params) {

        table.DataTable().search(JSON.stringify(params)).draw();
    };

    // 农作物
    var viewCrops = function (id = '') {
        $('#crops-modal').modal('show');
        initCropsTable();
    };

    // 药剂
    var viewMedicaments = function (id = '') {
        $('#medicaments-modal').modal('show');
        //if(!isLoadMedicamentsTable){
            initMedicamentsTable();
        //}
    };


    return {
        init: function() {
            initTable();

            this.onEvent();
        },

        onEvent : function(){

            // 选择农作物
            $('.select-crops').on('click', function(){
                viewCrops();
            });

            // 选择药剂
            $('.select-medicaments').on('click', function(){
                viewMedicaments();
            });

            // 全选 / 取消全选
            $(document).find('.sellectall-btn').on('click', function(){
                var form = $(this).parents('.datatable-form');
                var _this = $(this);

                var value = $(this).attr('data-value');
                if(value == 1){
                    form.find('.check-item').not(':disabled').prop('checked', true);
                    _this.attr('data-value', 2);
                    _this.empty().html('取消全选');
                }else{
                    form.find('.check-item').not(':disabled').prop('checked', false);
                    _this.attr('data-value', 1);
                    _this.empty().html('全选');
                }
            });

            // 确定添加农作物
            $(document).find('.saveCrops-btn').on('click', function(){
                var form = $(this).parents('.modal').find('.datatable-form');
                var _this = $(this);

                if(form.find('.check-item').not(':disabled').filter(':checked').length <= 0){
                    layer.msg('请至少选择一条数据');
                    return false;
                }
                var ids = '';
                $(form).find('.check-item').not(':disabled').filter(':checked').each(function () {
                    ids += ',' + $(this).val();
                });

                ids = ids.substr(1);
                var cropIds = $('.cropIds').val();
                if(cropIds){
                    cropIds = cropIds + ',' + ids;
                }else{
                    cropIds = ids;
                }
                $('.cropIds').val(cropIds);

                form.find('.check-item').not(':disabled').filter(':checked').each(function () {
                    var id = $(this).val();
                    var name = $(this).data('name');
                    var tagName = '<span class="tag label label-info" style="margin-right: 4px;" data-tagid="'+id+'">'+name+'<span data-role="remove" class="remove-btn"></span></span>';
                    $('.crops-group').find('.bootstrap-tagsinput').append(tagName);
                });

                $('#crops-modal').modal('hide');
            });

            // 确定添加药剂
            $(document).find('.saveMedicaments-btn').on('click', function(){
                var form = $(this).parents('.modal').find('.datatable-form');
                var _this = $(this);

                if(form.find('.check-item').not(':disabled').filter(':checked').length <= 0){
                    layer.msg('请至少选择一条数据');
                    return false;
                }
                var ids = '';
                form.find('.check-item').not(':disabled').filter(':checked').each(function () {
                    ids += ',' + $(this).val();
                });

                ids = ids.substr(1);
                var medicamentIds = $('.medicamentIds').val();
                if(medicamentIds){
                    medicamentIds = medicamentIds + ',' + ids;
                }else{
                    medicamentIds = ids;
                }
                $('.medicamentIds').val(medicamentIds);

                form.find('.check-item').not(':disabled').filter(':checked').each(function () {
                    var id = $(this).val();
                    var name = $(this).data('name');
                    var tagName = '<span class="tag label label-info" style="margin-right: 4px;" data-tagid="'+id+'">'+name+'<span data-role="remove" class="remove-btn"></span></span>';
                    $('.medicaments-group').find('.bootstrap-tagsinput').append(tagName);
                });

                $('#medicaments-modal').modal('hide');
            });

            // 移除标签
            $(document).find('.crops-group').on('click', '.remove-btn', function(){
                $(this).parents('.label-info').remove();
                var ids = '';
                $('.crops-group').find('.label-info').each(function(){
                    ids += ',' + $(this).data('tagid');
                });
                $('.cropIds').val(ids.substr(1));
            });
            $(document).find('.medicaments-group').on('click', '.remove-btn', function(){
                $(this).parents('.label-info').remove();
                //var medicamentIds = $('.medicamentIds').val();
                //var medicamentIdsArr = medicamentIds.split(',');
                var ids = '';
                $('.medicaments-group').find('.label-info').each(function(){
                    ids += ',' + $(this).data('tagid');
                });
                $('.medicamentIds').val(ids.substr(1));
            });

            // 表单提交
            $('.save-btn').on('click', function(){
                var form = this.form;
                var _this = $(this);

                if(form.name.value=='') {
                    layer.msg("请输入名称!");
                    form.name.focus();
                    return;
                }
                if(form.crops.value=='') {
                    layer.msg("请选择发生农作物!");
                    return;
                }
                if(form.medicaments.value=='') {
                    layer.msg("请选择适用药剂!");
                    return;
                }
                if(imgcount > total) {  //检测图片数量
                    layer.msg("图片最多添加"+total+"张，请删除多余图片");
                    return;
                }

                var _data = $(form).serializeObject();
                _this.prop("disabled", true);

                $.ajax({
                    url : save_url,
                    type : 'post',
                    dataType : 'json',
                    contentType : "application/json; charset=utf-8",
                    data : JSON.stringify(_data),
                }).done(function(data) {
                    if (data.code == 1) {
                        layer.msg('保存成功');
                        window.location.href= data.url; //加载页面数据
                    } else {
                        _this.prop("disabled", false);
                        layer.msg(data.msg);
                    }
                });
            });
        }
    };

}();

$(function() {
    Harm.init();
});
